// pages/meal/detail/detail.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    detail: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getMealDetail()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getMealDetail: function() {
    let that = this
    wx.showLoading({
      title: app.globalData.loadText,
      mask: true
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/setmeal/get-by-id?access_token=' + accessToken,
        data: {
          setmeal_id: that.data.id
        },
        success: res => {
          if(res.data.status === 1) {
            that.setData({
              detail: res.data.data.setmeal
            },() => {
              wx.hideLoading()
            })
          }
        }
      })
    })
  },

  buyMeal: function() {
    let that = this
    wx.showLoading({
      title: app.globalData.loadText,
      mask: true
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/wxpay/setmeal?access_token=' + accessToken,
        data: {
          setmeal_id: that.data.id
        },
        success: res => {
          if (res.data.status === 1) {
            wx.hideLoading()
            wx.showModal({
              title: '提示',
              content: '购买成功',
              showCancel: false,
              success: res => {
                if(res.confirm) {
                  wx.reLaunch({
                    url: '/pages/success/success',
                  })
                }
              }
            })
          }
        }
      })
    })
  }
})